﻿using System;
using System.Collections.Generic;
using System.Text;
using Barbar.MapReport.Common.Drawing.Commands;
using Barbar.MapReport.Common.Drawing;
using JsonSharp.Collections;
using JsonSharp.Values;

namespace Barbar.MapReport.HtmlRender.Operations {
  internal class AddGraphsOperation : RenderBaseOperation {
    private AddGraphsCommand m_Command;

    public AddGraphsOperation(AddGraphsCommand command) {
      m_Command = command;
    }

    #region RenderBaseOperation Members

    protected override void RenderInternal(RenderingContext context) {
      decimal maxValue = 0;
      foreach (MultipleBusinessGeoPoint point in m_Command.Points) {
        foreach (decimal value in point.Values) {
          if (maxValue < value)
            maxValue = value;
        }
      }

      foreach (MultipleBusinessGeoPoint point in m_Command.Points) {
        decimal[] values = new decimal[point.Values.Length];
        decimal localMaximum = 0;
        for (int i = 0; i < point.Values.Length; i++) {
          values[i] = (point.Values[i] * m_Command.MaxHeight) / maxValue;
          if (point.Values[i] > localMaximum)
            localMaximum = point.Values[i];
        }

        JsonArrays clientColors = new JsonArrays();
        JsonArrays clientValues = new JsonArrays();
        for (int i = 0; i < m_Command.Colors.Count; i++) {
          clientColors.Add(new JsonColorValue(m_Command.Colors[i].Color));
          clientValues.Add(new JsonNumberValue(values[i]));
        }

        string title = ResolveTitle(values[0], localMaximum, point.Name);

        JsonObjects graph = new JsonObjects();
        graph.Add(new JsonStringValue("colors"), clientColors);
        graph.Add(new JsonStringValue("values"), clientValues);
        graph.Add(new JsonStringValue("lat"), new JsonNumberValue(point.Latitude));
        graph.Add(new JsonStringValue("lng"), new JsonNumberValue(point.Longitude));
        graph.Add(new JsonStringValue("columnWidth"), new JsonNumberValue(m_Command.ColumnWidth));
        graph.Add(new JsonStringValue("title"), new JsonStringValue(title));
        graph.Add(new JsonStringValue("titleColor"), new JsonColorValue(m_Command.TitleColor.Color));

        context.Write(JavaScriptFunction.AddGraph, graph);
      }
    }

    private string ResolveTitle(decimal firstValue, decimal maximalValue, string name) {
      string title = m_Command.ValueFormatString;
      if (String.IsNullOrEmpty(title))
        return String.Empty;

      title = title.Replace("{FirstValue}", Convert.ToString(firstValue));
      title = title.Replace("{MaximalValue}", Convert.ToString(maximalValue));

      string realName = String.Empty;
      if (!String.IsNullOrEmpty(name))
        realName = name;

      title = title.Replace("{Name}", realName);
      return title;
    }

    #endregion
  }
}
